package com.salary.utils.reader;


import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 每日扣款表
 */
public class MonthlyDeductionReader extends DataReader<Map<String, Double>> {
    private static final Logger logger = LoggerFactory.getLogger(MonthlyDeductionReader.class);

    /**
     * 从扣款表读取扣款数据
     *
     * @param deductionFilePath 扣款表文件路径
     * @return 姓名到扣款金额的映射
     */
    @Override
    public Map<String, Double> readData(String deductionFilePath) {
        Map<String, Double> deductionData = new HashMap<>();

        try (FileInputStream fis = new FileInputStream(deductionFilePath);
             Workbook workbook = WorkbookFactory.create(fis)) {

            Sheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                logger.error("扣款表中未找到工作表");
                return deductionData;
            }

            logger.info("从扣款表的'" + sheet.getSheetName() + "'工作表读取数据");

            // 使用通用方法查找列
            Map<String, Integer> columnIndices = findColumnIndices(sheet, new String[]{"姓名", "金额"});

            // 验证是否找到必要的列
            if (!columnIndices.containsKey("姓名") || !columnIndices.containsKey("金额")) {
                logger.error("扣款表中未找到必要的列");
                return deductionData;
            }

            int nameColIndex = columnIndices.get("姓名");
            int amountColIndex = columnIndices.get("金额");

            //
            // 从第二行开始读取数据（跳过表头）
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                Cell nameCell = row.getCell(nameColIndex);
                if (nameCell == null) continue;

                String name = getCellValueAsString(nameCell).trim();
                if (name.isEmpty()) continue;

                Cell amountCell = row.getCell(amountColIndex);
                if (amountCell == null) continue;

                double amount = getCellValueAsDouble(amountCell);

                // 如果金额为0，则尝试直接读取单元格的字符串值并转换
                if (amount == 0) {
                    try {
                        String amountStr = getCellValueAsString(amountCell).trim();
                        if (!amountStr.isEmpty()) {
                            // 移除可能的货币符号和千分位分隔符
                            amountStr = amountStr.replace(",", "").replace("¥", "").replace("￥", "");
                            amount = Double.parseDouble(amountStr);
                        }
                    } catch (NumberFormatException e) {
                        // 忽略解析错误
                    }
                }

                if (amount > 0) {
                    // 添加到现有值或创建新条目
                    deductionData.put(name, deductionData.getOrDefault(name, 0.0) + amount);
                    logger.info("读取到扣款数据: " + name + " - " + amount);
                }
            }

            logger.info("成功从扣款表读取了 " + deductionData.size() + " 条记录");

        } catch (IOException e) {
            logger.error("读取扣款表文件失败: " + e.getMessage(), e);
        }

        return deductionData;
    }
}
